<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-01 15:35:09
 * @LastEditTime: 2020-03-23 23:30:15
 * @LastEditors: Please set LastEditors
 -->
<!doctype html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport"
		content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0,viewport-fit=cover" />
	<meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
	<title>Hello APP</title>
	<link rel="stylesheet" type="text/css" href="../css/vant.css">
	<link rel="stylesheet" type="text/css" href="../css/base.css" />
	<script type="text/javascript" src="../script/jquery.js"></script>
	<script type="text/javascript" src="../script/vue.min.js"></script>
	<script type="text/javascript" src="../script/vant.min.js"></script>
	<script type="text/javascript" src="../script/fastclick.js"></script>
	<script type="text/javascript" src="../script/base.js"></script>
	<script type="text/javascript" src="../script/db.js"></script>
	<script type="text/javascript" src="../script/jquery.signalR-2.4.1.min.js"></script>
	<script>
		var scriptBlock = document.createElement('script');
		scriptBlock.src = 'http://' + APP.serverIP() + '/signalr/hubs';
		try {
			document.getElementsByTagName('head')[0].appendChild(scriptBlock);
		} catch (e) {

		}

	</script>
	<script type="text/javascript" src="../script/signalr-mediate.js"></script>
	<style type="text/css">
		body {
			background: #efefef;
		}

		.body-no-head {
			height: calc(100% - 50px);
			position: relative;
		}
	</style>
</head>

<body>
	<div id="app" v-cloak>
		<div class="init-full">
			<div class="body-no-head">

			</div>

			<van-tabbar inactive-color="#9e9e9e" active-color="#1daaff" v-model="tabbarActive" @change="changeTabbar">
				<van-tabbar-item v-show="isManager" icon="home-o">主页</van-tabbar-item>
				<van-tabbar-item icon="chat-o" :info="dot || ''">消息</van-tabbar-item>
				<van-tabbar-item icon="orders-o">栏目</van-tabbar-item>
				<van-tabbar-item icon="user-o">我的</van-tabbar-item>
			</van-tabbar>
		</div>
	</div>
</body>
<script type="text/javascript">
	var vm;
	apiready = function () {

		DB.initDatabase(function () {
			DB.createTable(function () {

			});
		})

		var mine;
		var isOpenChatList = false;

		var friend = '';
		var groups = '';

		APP.exitApp();

		var demo = api.require('xGprinterTsc');

		api.addEventListener({
			name: 'printStatus'
		}, function (ret) {
			console.log(JSON.stringify(ret.value.printData))
			ret.value.printData.map((item) => {
				console.log(JSON.stringify(item))
				vm.checkPrintStatus(item)
			})
		})//标签打印相关

		api.addEventListener({
			name: 'setPrint'
		}, function (ret) {
			vm.setPrint()
		})  //标签打印相关

		api.addEventListener({
			name: 'setUnRedMsg'
		}, function (ret, err) {
			vm.dot = ret.value.dot;
		});

		api.addEventListener({
			name: 'getUnReadMsgRepeat'
		}, function (ret, err) {
			APP.ajax('getGroupList', { userID: APP.getUserInfo().UserID }, function (res) {
				groups = [];
				for (var i = 0; i < res.ds.length; i++) {
					groups.push({
						groupname: res.ds[i].GroupName,
						id: res.ds[i].GroupID.toString(),
						avatar: "../image/group.png" //群组头像
					})
				}
				vm.getUnReadMsg();
			})
		});



		api.addEventListener({
			name: 'openChatList'
		}, function (ret, err) {
			isOpenChatList = ret.value.isOpenChatList;
		});

		api.addEventListener({
			name: 'sendMineMsg'
		}, function (ret, err) {
			var msgObj = ret.value.msgObj;

			var sendmsg = function () {
				if (msgObj.type == 'friend') {
					$.signalrApi.server.chatMsg(mine.contextIDs, mine.id, msgObj.toUserID, msgObj.content);
				}
				else {
					$.signalrApi.server.groupMsg(mine.contextIDs, mine.id, msgObj.toUserID, msgObj.content);
				}
			}



			try {
				$.signalrApi.server.clientLive();
				sendmsg();
			} catch (e) {
				$.signalrApi.start(function () {
					$.signalrApi.server.clientConnect(APP.getUserInfo().UserID);
					setTimeout(function () {
						sendmsg();
					}, 500)
				});
			}


		});

		// var ajpush = api.require('ajpush');

		// function listenJPush() {
		// 	var ListenerType = '';
		// 	if (api.systemType == "android") {
		// 		ListenerType = 'appintent';
		// 		ajpush.init(function (ret) {
		// 			var param = { alias: APP.getUserInfo().UserID };
		// 			ajpush.bindAliasAndTags(param, function (ret) {

		// 			});
		// 		});
		// 	} else if (api.systemType == "ios") {
		// 		ListenerType = 'noticeclicked';
		// 		var param = { alias: APP.getUserInfo().UserID };
		// 		ajpush.bindAliasAndTags(param, function (ret) {

		// 		});
		// 	}

			// api.addEventListener({ name: ListenerType }, function (ret, err) {
			// 	var data = null;
			// 	if (api.systemType == "android") {
			// 		data = ret.appParam.ajpush.extra.data;
			// 	} else {
			// 		data = ret.value.extra.data;
			// 	}

			// 	if (data) {
			// 		var data_json = JSON.parse(data);
			// 		if (data_json.type == 'chatmsg') {
			// 			APP.ajax('getInfoByID', { msgID: data_json.msg, type: 1 }, function (res) {
			// 				var row = {
			// 					id: res.ds[0].UserID.toString(),
			// 					groupname: '',
			// 					username: res.ds[0].UserName,
			// 					avatar: res.ds[0].HeadImg,
			// 					type: 'friend'
			// 				}
			// 				api.openWin({
			// 					name: 'chatListDetail',
			// 					url: 'chat/chatListDetail.html',
			// 					reload: true,
			// 					slidBackEnabled: false,
			// 					allowEdit: true,
			// 					pageParam: {
			// 						row: row
			// 					}
			// 				})
			// 			})
			// 		} else if (data_json.type == 'groupmsg') {
			// 			APP.ajax('getInfoByID', { msgID: data_json.msg, type: 2 }, function (res) {
			// 				var row = {
			// 					id: res.ds[0].GroupID.toString(),
			// 					groupname: res.ds[0].GroupName,
			// 					username: '',
			// 					avatar: '../../image/ql.png',
			// 					type: 'group'
			// 				}
			// 				api.openWin({
			// 					name: 'chatListDetail',
			// 					url: 'chat/chatListDetail.html',
			// 					reload: true,
			// 					slidBackEnabled: false,
			// 					allowEdit: true,
			// 					pageParam: {
			// 						row: row
			// 					}
			// 				})
			// 			})
			// 		}
			// 	}

			// })
		// }

		// listenJPush();


		var recMp3 = api.require('recMp3');
		var audioStreamer = api.require('audioStreamer');

		var signalrTimer = null;

		$.clientCallBacks = {};
		var signalRHelper = function () {
			$.signalrApi({
				serverUrl: "http://" + APP.serverIP(),
				clientHub: "IMHub",
				clientEvents: [
					{
						name: "onClientConnect",
						method: function (data) {
							$.clientCallBacks["onClientConnect"](data);
						}
					},
					{
						name: "onChatMsg",
						method: function (userId, msg, timestap) {
							$.clientCallBacks["onChatMsg"](userId, msg, timestap);
						}
					},
					{
						name: "onGroupMsg",
						method: function (userId, groupId, msg, timestap) {
							$.clientCallBacks["onGroupMsg"](userId, groupId, msg, timestap);
						}
					},
					{
						name: "onUserOnlineNotify",
						method: function (userInfo) {
							$.clientCallBacks["onUserOnlineNotify"](userInfo);
						}
					},
					{
						name: "onUserOfflineNotify",
						method: function (userId) {
							$.clientCallBacks["onUserOfflineNotify"](userId);
						}
					}
				]
			});
			//socket连接
			function signalrConnect() {
				$.signalrApi.start(function () {
					$.signalrApi.server.clientConnect(APP.getUserInfo().UserID);
				});
			}
			signalrConnect();

			signalrTimer = setInterval(function () {
				try {
					$.signalrApi.server.clientLive();
				} catch (e) {
					$.signalrApi.start(function () {
						$.signalrApi.server.clientConnect(APP.getUserInfo().UserID);
					});
				}

			}, 2000);
		}


		vm = new Vue({
			el: '#app',
			data: {
				showLoading: false,
				tabbarActive: 2,
				dot: 0,
				isManager: false
			},
			created: function () {
				var that = this;
				if (api.safeArea.bottom) {
					setTimeout(function () {
						$('.van-tabbar').css({
							// 'height': 50 + api.safeArea.bottom + 'px',
							'padding-bottom': api.safeArea.bottom + 'px'
						})
					}, 300)


				}
				that.getUserRole();
				that.initChat();

				//that.setPrint();//标签打印

				// api.openFrame({
				// 	name: 'index',
				// 	url: 'index.html',
				// 	rect: {
				// 		x: 0,
				// 		y: 0,
				// 		w: api.winWidth,
				// 		h: api.winHeight - 50 - api.safeArea.bottom
				// 		// h: api.winHeight - api.safeArea.bottom
				// 	}
				// });
			},
			methods: {
				setPrint() {//标签打印相关
					var that = this
					demo.getUsbDeviceList(function (ret, err) {
						// alert(JSON.stringify(ret));
						if (!err) {
							console.log(JSON.stringify(ret))
							if (ret.data.length) {
								that.deviceName = ret.data[0].deviceName
								that.connectUSB()
							} else {
								api.confirm({
									title: '提示',
									msg: '是否确认取消连接打印机',
									buttons: ['确定', '取消']
								}, function (ret, err) {
									var index = ret.buttonIndex;
									if (ret.buttonIndex != 1) {
										that.setPrint()
									}
								});
							}
						} else {
							api.confirm({
								title: '提示',
								msg: '是否确认取消连接打印机',
								buttons: ['确定', '取消']
							}, function (ret, err) {
								var index = ret.buttonIndex;
								if (ret.buttonIndex != 1) {
									that.setPrint()
								}
							});
						}
					})
				},
				connectUSB() {
					var that = this
					demo.connectUsb({
						deviceName: that.deviceName
					}, function (ret, err) {
						// alert(JSON.stringify(ret));
						if (!err) {
							if (ret.evenType == 'onSuccess') {
								api.toast({
									msg: that.deviceName + '打印机连接成功!',
									duration: 2000,
									location: 'bottom'
								});
							}
						} else {
							api.alert({
								title: '打印机USB连接报错!',
								msg: JSON.stringify(err),
							}, function (alertRet, alerterr) {
								if (alertRet) {
									that.setPrint()
								}
							});
						}
					})
				},

				checkPrintStatus(code) {
					var that = this
					console.log(JSON.stringify(code))
					var ret = demo.getConnectState();
					// alert(JSON.stringify(ret));
					if (ret) {
						api.toast({
							msg: that.deviceName + '打印机连接正常!',
							duration: 2000,
							location: 'bottom'
						});
						demo.checkState(function (stateRet, stateErr) {
							// alert(JSON.stringify(ret))
							if (ret) {
								api.toast({
									msg: that.deviceName + '打印机状态正常!',
									duration: 2000,
									location: 'bottom'
								});
								that.printLabel(code)
							} else {
								api.alert({
									title: '提示',
									msg: '打印机状态异常,请检查!' + JSON.stringify(stateErr),
								}, function (alertRet, alerterr) {
									if (alertRet) {
										that.setPrint()
									}
								});
							}
						});
					} else {
						api.alert({
							title: '提示',
							msg: '打印机连接异常,请检查!',
						}, function (alertRet, alerterr) {
							if (alertRet) {
								that.setPrint()
							}
						});
					}
				},
				printLabel(print) {
					try {
						var that = this
						// alert(JSON.stringify('开始打印了'))
						var month = '(' + (new Date().getMonth() + 1) + ')月份标签'
						demo.printTsc({
							rows: [
								// { lineType: 'size', width: 100, height: 80.4 },
								{ lineType: 'size', width: 70, height: 50 },
								{ lineType: 'gap', m: 2, n: 0 },
								{ lineType: 'reference', x: 0, y: 0 },
								{ lineType: 'tear', data: 'true' },
								{ lineType: 'addQueryPrinterStatus', status: 'ON' },
								{ lineType: 'cls' },
								{
									lineType: 'addPeel',//设置打印机剥离模式
									tear: 'ON'// ON/OFF 是否开启
								},
								{
									lineType: 'qrcode', //绘制qrcode,
									x: 160,
									y: 120,
									level: 'L',  //L|M|H|Q
									cellwith: 9,
									rotation: 0, // 0|90|180|270
									data: print.boxCode
								},
								{//绘制文本
									lineType: 'text',
									x: 160,
									y: 48,
									font: 13,
									rotation: 0,
									xScal: 1,
									yScal: 1,
									data: print.boxCode
								},
								{//绘制文本
									lineType: 'text',
									x: 150,
									y: 48,
									font: 13,
									rotation: 0,
									xScal: 1,
									yScal: 1,
									data: print.ProductName
								},
								// {//绘制文本
								//     lineType: 'text',
								//     x: 250,
								//     y: 48,
								//     font: 13,
								//     rotation: 0,
								//     xScal: 1,
								//     yScal: 1,
								//     data: '宁波劳伦斯表面技术有限公司'
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 310,
								//     y: 88,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: month
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 60,
								//     y: 110,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.ProductCode
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 60,
								//     y: 170,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.ProductionNO
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 60,
								//     y: 240,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.date
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 180,
								//     y: 300,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.time
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 60,
								//     y: 360,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.BaoZhangQTY
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 60,
								//     y: 420,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.lastBoxCode
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 60,
								//     y: 480,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.EquipmentID
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 60,
								//     y: 540,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.empolorName
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 390,
								//     y: 120,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.frontProductName
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 390,
								//     y: 160,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.afterProductName
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 390,
								//     y: 220,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.batch
								// },
								// {
								//     lineType: 'qrcode', //绘制qrcode,
								//     x: 390,
								//     y: 280,
								//     level: 'L',  //L|M|H|Q
								//     cellwith: 9,
								//     rotation: 0, // 0|90|180|270
								//     data: print.boxCode
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 390,
								//     y: 520,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.boxCode
								// },
								// {//绘制文本
								//     lineType: 'text',
								//     x: 390,
								//     y: 560,
								//     font: 13,
								//     rotation: 0,
								//     xscal: 1,
								//     yscal: 1,
								//     data: print.GX
								// },
								{ lineType: 'addPrint', m: 1, n: 1 },
								{ lineType: 'queryPrinterStatus' },
							],
							isQueryState: true,
						}, function (ret, err) {
							if (ret) {
								api.sendEvent({
									name: 'refreshProductReport',
									extra: {
										ret: ret
									}
								})
							} else {
								api.sendEvent({
									name: 'refreshProductReport',
									extra: {
										err: err
									}
								})
							}
						});
					}
					catch (e) {
						api.alert({
							title: '提示',
							msg: '打印方法报错' + e,
						}, function (alertRet, alerterr) {
						});
					}


				},//标签打印相关
				getUserRole() {
					var that = this;
					APP.ajax('AP_GetUserNM', {}, function (res) {
						var roleList = res.ds;
						// console.log(JSON.stringify(roleList));
						for (var i = 0; i < roleList.length; i++) {
							if (roleList[i].APFunName.indexOf('营销报表') >= 0) {

								that.isManager = true;
								that.tabbarActive = 0;
								that.changeTabbar(0);
							}
						}
						if (!that.isManager) {
							that.changeTabbar(2);
						}

					})
				},


				initChat: function () {
					var that = this;
					APP.ajax('GetChatUser', { userID: APP.getUserInfo().UserID }, function (res) {
						userData = res.ds[0];
						mine = {
							username: res.ds[0].UserName,
							id: res.ds[0].UserID.toString(),
							status: "online",
							sign: res.ds[0].Sign,
							avatar: res.ds[0].HeadImg
						}
						var friendInfo = [{
							"groupname": "劳伦斯用户",
							id: 1
						}];

						groups = [];
						friend = [];
						//用户列表
						for (var i = 0; i < res.ds1.length; i++) {
							friend.push({
								username: res.ds1[i].UserName,
								id: res.ds1[i].UserID.toString(),
								status: res.ds1[i].ContextIDs ? "online" : 'offline',
								sign: res.ds1[i].Sign,
								avatar: res.ds1[i].HeadImg,
								contextIDs: res.ds1[i].ContextIDs
							})
						}
						//群列表
						for (var i = 0; i < res.ds2.length; i++) {
							groups.push({
								groupname: res.ds2[i].GroupName,
								id: res.ds2[i].GroupID.toString(),
								avatar: "../../image/ql.png" //群组头像
							})
						}

						friendInfo[0].list = friend;

						$.clientCallBacks["onClientConnect"] = function (contextID) {
							mine["contextIDs"] = contextID;
						}
						$.clientCallBacks["onChatMsg"] = function (userId, msg, timestamp) {
							var fs = [];
							for (var u in friend) {
								if (friend[u].id == userId) {
									fs.push(friend[u])
								}
							}
							if (fs.length > 0) {
								var msgObj = {
									groupname: '',
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: fs[0].id,
									type: "friend", //聊天窗口来源类型，从发送消息传递的to里面获取
									content: msg,
									cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: timestamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								}
								api.sendEvent({
									name: 'getChatMsg',
									extra: {
										msgObj: msgObj
									}
								});
								if (isOpenChatList) {
									api.sendEvent({
										name: 'checkChatList',
										extra: {
											msgObjArray: [msgObj]
										}
									});

								} else {
									that.setChatStorage([msgObj]);
									if (msg) {
										that.dot++;
									}

								}


								if (msg) {

									audioStreamer.onNormal();
									audioStreamer.openPlayer({
										path: 'widget://image/chat/msg.mp3',
									}, function (ret) {

									});
								}

							}
						}
						$.clientCallBacks["onGroupMsg"] = function (userId, groupId, msg, timestamp) {

							var getGroupList = function () {
								APP.ajax('getGroupList', { userID: APP.getUserInfo().UserID }, function (res) {
									groups = [];
									for (var i = 0; i < res.ds.length; i++) {
										groups.push({
											groupname: res.ds[i].GroupName,
											id: res.ds[i].GroupID.toString(),
											avatar: "../../image/ql.png" //群组头像
										})
									}
									onGroupMsgGet();
								})
							}

							var onGroupMsgGet = function () {
								var fs = [];
								for (var u in friend) {
									if (friend[u].id == userId) {
										fs.push(friend[u])
									}
								}
								var gs = [];
								for (var u in groups) {
									if (groups[u].id == groupId) {
										gs.push(groups[u])
									}
								}
								if (gs.length == 0) {
									getGroupList();
								}
								if (fs.length > 0) {
									//接收消息
									var msgObj = {
										groupname: gs[0].groupname,
										username: fs[0].username,
										avatar: fs[0].avatar,
										id: groupId,
										type: "group", //聊天窗口来源类型，从发送消息传递的to里面获取
										content: msg,
										cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
										mine: false,  //是否我发送的消息，如果为true，则会显示在右方
										fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
										timestamp: timestamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
									};


									api.sendEvent({
										name: 'getChatMsg',
										extra: {
											msgObj: msgObj
										}
									});

									if (isOpenChatList) {
										api.sendEvent({
											name: 'checkChatList',
											extra: {
												msgObjArray: [msgObj]
											}
										});
									} else {
										that.setChatStorage([msgObj]);
										if (msg) {
											that.dot++;
										}
									}


								}
							}

							onGroupMsgGet();
							if (msg) {
								audioStreamer.onNormal();
								audioStreamer.openPlayer({
									path: 'widget://image/chat/msg.mp3',
								}, function (ret) {

								});
							}



						}


						$.clientCallBacks["onUserOnlineNotify"] = function (info) {

						}

						$.clientCallBacks["onUserOfflineNotify"] = function (userId) {

						}

						signalRHelper();
						//获取未读信息
						setTimeout(function () {
							that.getUnReadMsg();
						}, 2000);
					})
				},
				setChatStorage: function (msgObjArray) {
					var that = this;
					var sql = "select * from Chat where UserID='" + APP.getUserInfo().UserID + "'";
					var chatPersonList_sql = DB.selectSqlSync(sql);
					if (chatPersonList_sql.length) {
						var chatPersonList = JSON.parse(chatPersonList_sql[0].JSONStr1);
						for (var i in msgObjArray) {
							if (msgObjArray[i].content) {
								if (msgObjArray[i].type == 'group') {
									msgObjArray[i].avatar = '../../image/ql.png';
								}
								var x = 0;
								for (var j in chatPersonList) {
									if (parseInt(chatPersonList[j].id) == parseInt(msgObjArray[i].id) && chatPersonList[j].type == msgObjArray[i].type) {
										x = 1;
										msgObjArray[i].unReadNum = (parseInt(chatPersonList[j].unReadNum) || 0) + 1;
										chatPersonList[j] = msgObjArray[i];
									}
								}
								if (x == 0) {
									msgObjArray[i].unReadNum = 1;
									chatPersonList.unshift(msgObjArray[i]);
								}
							}

						}

						var sql = "update Chat set JSONStr1='" + JSON.stringify(chatPersonList).replace(/\'/g, '\'\'') + "',UpdateTime='" + APP.getFormatDate2() + "' where ChatID='" + chatPersonList_sql[0].ChatID + "'";
						DB.executeSql(sql, function () {

						})

					} else {
						var sql = "insert into Chat (UserID,JSONStr1,CreateTime) values ('" + APP.getUserInfo().UserID + "','" + JSON.stringify(msgObjArray).replace(/\'/g, '\'\'') + "','" + APP.getFormatDate2() + "')"
						DB.executeSql(sql, function () {

						})
					}
				},
				getUnReadMsg: function () {
					var that = this;
					APP.ajax('getUnReadMsg', { userID: APP.getUserInfo().UserID }, function (res) {
						var unReadMsgObj = [];
						for (var i = 0; i < res.ds.length; i++) {
							//每条消息重新发送给当前用户
							var fs = [];
							for (var u in friend) {
								if (friend[u].id == res.ds[i].FromUserID) {
									fs.push(friend[u])
								}
							}
							if (fs.length > 0) {
								//接收消息
								var msgObj = {
									groupname: '',
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: fs[0].id,
									type: "friend",  //聊天窗口来源类型，从发送消息传递的to里面获取
									content: res.ds[i].Content,
									cid: 0,  //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: res.ds[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								};

								unReadMsgObj.push(msgObj)

							}
						}
						for (var i = 0; i < res.ds1.length; i++) {
							var fs = [];
							for (var u in friend) {
								if (friend[u].id == res.ds1[i].FromUserID) {
									fs.push(friend[u])
								}
							}
							var gs = [];
							for (var u in groups) {
								if (groups[u].id == res.ds1[i].GroupID) {
									gs.push(groups[u])
								}
							}
							if (fs.length > 0) {
								//接收消息
								var msgObj = {
									groupname: gs[0].groupname,
									username: fs[0].username,
									avatar: fs[0].avatar,
									id: res.ds1[i].GroupID,
									type: "group",  //聊天窗口来源类型，从发送消息传递的to里面获取
									content: res.ds1[i].Content,
									cid: 0, //消息id，可不传。除非你要对消息进行一些操作（如撤回）
									mine: false,  //是否我发送的消息，如果为true，则会显示在右方
									fromid: fs[0].id,  //消息的发送者id（比如群组中的某个消息发送者），可用于自动解决浏览器多窗口时的一些问题
									timestamp: res.ds1[i].CreateTimeStamp * 1000 - 8 * 60 * 60 * 1000 //服务端时间戳毫秒数。注意：如果你返回的是标准的 unix 时间戳，记得要 *1000
								};

								unReadMsgObj.push(msgObj)

							}
						}

						if (isOpenChatList) {
							api.sendEvent({
								name: 'checkChatList',
								extra: {
									msgObjArray: unReadMsgObj
								}
							});
						} else {
							if (unReadMsgObj.length) {
								that.dot = unReadMsgObj.length;
								audioStreamer.onNormal();
								audioStreamer.openPlayer({
									path: 'widget://image/chat/msg.mp3',
								}, function (ret) {

								});
							}
						}

					})
				},
				changeTabbar(index) {
					var url = '';
					if (index == 0) {
						url = 'index';
					} else if (index == 1) {
						url = 'chat/chatList';
						this.tabbarActive = -1;
					} else if (index == 2) {
						url = 'module';
					} else if (index == 3) {
						url = 'personalCenter';
					}

					if (index == 1) {
						api.openWin({
							name: url,
							url: url + '.html',
							reload: true,
							slidBackEnabled: false,
							allowEdit: true,
							pageParam: {
								historyData: null
							}
						})
					} else {
						api.openFrame({
							name: url,
							url: url + '.html',
							rect: {
								x: 0,
								y: 0,
								w: api.winWidth,
								h: api.winHeight - 50 - api.safeArea.bottom
							}
						});
					}




				}
			}
		})
	};
</script>

</html>